﻿package src.utils{
	import flash.display.DisplayObject;
	import flash.ui.Keyboard;
	import flash.display.Sprite;
	import flash.events.FocusEvent;
	import flash.events.KeyboardEvent;
	public class Keys {
		private var pressKeys:Array = new Array(200);

		public function Keys() {
		}
		
		public function addKeysListeners(keysStateListener:DisplayObject):void {
			keysStateListener.addEventListener(FocusEvent.FOCUS_OUT, disableAllKeys, false, 0, true);
			keysStateListener.addEventListener(KeyboardEvent.KEY_DOWN, keyDown, false, 0, true);
			keysStateListener.addEventListener(KeyboardEvent.KEY_UP, keyUp, false, 0, true);
		}
		
		public function removeKeysListeners(keysStateListener:DisplayObject):void {
			keysStateListener.removeEventListener(FocusEvent.FOCUS_OUT, disableAllKeys);
			keysStateListener.removeEventListener(KeyboardEvent.KEY_DOWN, keyDown);
			keysStateListener.removeEventListener(KeyboardEvent.KEY_UP, keyUp);
		}
		
		private function disableAllKeys(event:FocusEvent):void {
			for (var i:int = 0; i < pressKeys.length; i++ ) pressKeys[i] = false;
		}
		
		private function keyDown(event:KeyboardEvent):void {
			pressKeys[event.keyCode] = true;
			trace("key down: key code" + event.keyCode + " char code " + event.charCode);
		}
		
		private function keyUp(event:KeyboardEvent):void {
			pressKeys[event.keyCode] = false;
			//trace("key up: key code" + event.keyCode + " char code " + event.charCode);
		}
		
		public function isPressed(keyCode:int):Boolean {
			return (isInsideArrayLength(keyCode)) ? pressKeys[keyCode] : false;
		}
		
		private function isInsideArrayLength(index:int):Boolean {
			return (index > 0 && index < pressKeys.length) ? true : false;
		}
	}
}